import numpy as np
import os
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # 空间三维画图

# 获取列表的第二个元素
def takeFirst(elem):
    return elem[0]
def takeSecond(elem):
    return elem[1]
def takeThird(elem):
    return elem[2]

def xyz2xyzc(filein,fileout):
    fi=open(filein,"r+")
    fo=open(fileout,"w+")
    points=[]
    for i in range(0,11510):
        st=fi.readline()
        sp=st.split(" ")
        point=[]
        point.append(float(sp[0]))
        point.append(float(sp[1]))
        point.append(float(sp[2]))
        points.append(point)

    def getearline():#感觉取变化率最大的一段会好一点
        points.sort(key=takeFirst)
        low=points[0][0]
        kuadu=0.01
        mi=100
        ma=-100
        mami=[]
        lines=[]
        for i in range(0,11510):
            xx=points[i][0]
            yy=points[i][1]
            if (xx-low>kuadu):
                low=xx
                mami.append(ma-mi)
                lines.append(low)
                mi=100
                ma=-100
            else:
                if (yy>ma):
                    ma=yy
                if (yy<mi):
                    mi=yy
        '''
        print(len(mami))
        for i in range(len(mami)):
            print(mami[i])
        '''
        for i in range(len(mami)-1):
            bl=mami[i+1]/mami[i]
            if ((bl<0.667)and(mami[i]<1)):
                earlineright=lines[i]
            elif ((bl>1.5)and(mami[i]<1)):
                earlineleft=lines[i]
        return earlineleft,earlineright

    def getnoseline():#感觉取变化率最大的一段会好一点
        points.sort(key=takeThird)
        low=0
        kuadu=0.01
        mi=100
        ma=-100
        mami=[]
        lines=[]
        for i in range(0,11510):
            zz=points[i][2]
            if (zz>=0):
                yy=points[i][1]
                if (zz-low>kuadu):
                    low=zz
                    mami.append(ma-mi)
                    lines.append(low)
                    mi=100
                    ma=-100
                else:
                    if (yy>ma):
                        ma=yy
                    if (yy<mi):
                        mi=yy
        '''
        print(len(mami))
        for i in range(len(mami)):
            print(mami[i])
        '''
        getline=0
        for i in range(len(mami)):
            if ((getline==0) and (mami[i]<1.0)):
                noseline=lines[i]
                getline=1
        return noseline

    earlineleft,earlineright=getearline()
    noseline=getnoseline()
    print("noseline={}".format(noseline))

    facex=[]
    facey=[]
    facez=[]
    facepoint=[]

    earx=[]
    eary=[]
    earz=[]
    earpoint=[]

    nosex=[]
    nosey=[]
    nosez=[]
    nosepoint=[]

    mousex=[]
    mousey=[]
    mousez=[]
    mousepoint=[]

    eyex=[]
    eyey=[]
    eyez=[]
    eyepoint=[]

    for i in range(0,11510):
        xx=points[i][0]
        yy=points[i][1]
        zz=points[i][2]
        if (zz<0):
            if ((xx<earlineleft)or(xx>earlineright)):
                earx.append(xx)
                eary.append(yy)
                earz.append(zz)
            elif ((xx>=earlineleft)and(xx<=earlineright)):
                facex.append(xx)
                facey.append(yy)
                facez.append(zz)
        elif (zz>=0):
            if (yy<=0):
                if (zz>=noseline):
                    nosex.append(xx)
                    nosey.append(yy)
                    nosez.append(zz)
                elif (zz<noseline):
                    facex.append(xx)
                    facey.append(yy)
                    facez.append(zz)                
            elif (yy>0):
                if (zz>=noseline):
                    mousex.append(xx)
                    mousey.append(yy)
                    mousez.append(zz)
                elif (zz<noseline):
                    facex.append(xx)
                    facey.append(yy)
                    facez.append(zz)                           
        #print(point)
    def geteyeline():#感觉取变化率最大的一段会好一点
        fapoints=[]
        for i in range(len(facex)):
            fapoint=[]
            fapoint.append(facex[i])
            fapoint.append(facey[i])
            fapoint.append(facez[i])
            fapoints.append(fapoint)
        fapoints.sort(key=takeSecond)
        low=fapoints[0][1]
        kuadu=0.01
        gs=0
        gss=[]
        lines=[]
        for i in range(0,len(fapoints)):
            if (fapoints[i][2]>0):
                yy=fapoints[i][1]
                if (yy-low>kuadu):
                    low=yy
                    gss.append(gs)
                    lines.append(low)
                    gs=0
                else:
                    gs=gs+1
        
        print(len(gss))
        for i in range(len(gss)):
            print(gss[i])
        
        eyelineupget=0
        for i in range(len(gss)-1):
            if (((gss[i]<80) and (gss[i+1]>=80))and(eyelineupget==0)):
                eyelineup=lines[i]
                eyelineupget=1
            elif ((gss[i]>=80) and (gss[i+1]<80)):
                eyelinedown=lines[i]
        
        print("eyelineup={}".format(eyelineup))
        print("eyelinedown={}".format(eyelinedown))

        fapoints.sort(key=takeFirst)
        low=fapoints[0][0]
        kuadu=0.01
        gs=0
        gss=[]
        lines=[]
        for i in range(0,len(fapoints)):
            if ((fapoints[i][2]>0)and(fapoints[i][1]>=eyelineup)and(fapoints[i][1]<=eyelinedown)):
                xx=fapoints[i][0]
                if (xx-low>kuadu):
                    low=xx
                    gss.append(gs)
                    lines.append(low)
                    gs=0
                else:
                    gs=gs+1
        
        print(len(gss))
        for i in range(len(gss)):
            print(gss[i])
        
        eyelineleftget=0
        for i in range(len(gss)-1):
            if (((gss[i]<10) and (gss[i+1]>=10))and(eyelineleftget==0)):
                lefteyelineleft=lines[i]
                eyelineleftget=1
                '''
                ii=i+1
                while (gss[ii]>=10):
                    ii=ii+1
                lefteyelineright=lines[ii]
                '''
            elif ((gss[i]>=10) and (gss[i+1]<10)):
                righteyelineright=lines[i]
                '''
                ii=i
                while (gss[ii]>=10):
                    ii=ii-1
                righteyelineleft=lines[ii]
                '''
        
        print("lefteyelineleft={}".format(lefteyelineleft))
        #print("lefteyelineright={}".format(lefteyelineright))
        #print("righteyelineleft={}".format(righteyelineleft))
        print("righteyelineright={}".format(righteyelineright))
        return eyelineup,eyelinedown,lefteyelineleft,righteyelineright

    eyelineup,eyelinedown,eyelineleft,eyelineright=geteyeline()

    facexx=facex
    faceyy=facey
    facezz=facez
    facex=[]
    facey=[]
    facez=[]
    for i in range(len(facexx)):
        if ((facezz[i]>0) and (facexx[i]>=eyelineleft) and (facexx[i]<=eyelineright) and (faceyy[i]>=eyelineup) and (faceyy[i]<=eyelinedown)):
            eyex.append(facexx[i])
            eyey.append(faceyy[i])
            eyez.append(facezz[i])
        else:
            facex.append(facexx[i])
            facey.append(faceyy[i])
            facez.append(facezz[i])            
            


    facepoint.append(facex)
    facepoint.append(facey)
    facepoint.append(facez)

    eyepoint.append(eyex)
    eyepoint.append(eyey)
    eyepoint.append(eyez)

    earpoint.append(earx)
    earpoint.append(eary)
    earpoint.append(earz)

    nosepoint.append(nosex)
    nosepoint.append(nosey)
    nosepoint.append(nosez)

    mousepoint.append(mousex)
    mousepoint.append(mousey)
    mousepoint.append(mousez)



    facepointp=np.array(facepoint)
    eyepointp=np.array(eyepoint)
    earpointp=np.array(earpoint)
    nosepointp=np.array(nosepoint)
    mousepointp=np.array(mousepoint)
    #print(facepointp.shape)

    fig = plt.figure()
    ax = Axes3D(fig)
    ax.scatter(facepointp[0],facepointp[1],facepointp[2],c='b',label='facepoint',s=0.2)
    ax.scatter(eyepointp[0],eyepointp[1],eyepointp[2],c='m',label='facepoint',s=0.2)
    ax.scatter(earpointp[0],earpointp[1],earpointp[2],c='g',label='earpoint',s=0.2)
    ax.scatter(nosepointp[0],nosepointp[1],nosepointp[2],c='r',label='nosepoint',s=0.2)
    ax.scatter(mousepointp[0],mousepointp[1],mousepointp[2],c='k',label='mousepoint',s=0.2)

    ax.legend(loc='best')


    ax.set_zlabel('Z', fontdict={'size': 15, 'color': 'red'})
    ax.set_ylabel('Y', fontdict={'size': 15, 'color': 'red'})
    ax.set_xlabel('X', fontdict={'size': 15, 'color': 'red'})
    
    plt.show()

    for i in range(facepointp.shape[1]):
        fo.write("{} {} {} {}\n".format(facepointp[0][i],facepoint[1][i],facepoint[2][i],0))

    for i in range(eyepointp.shape[1]):
        fo.write("{} {} {} {}\n".format(eyepointp[0][i],eyepoint[1][i],eyepoint[2][i],1))

    for i in range(nosepointp.shape[1]):
        fo.write("{} {} {} {}\n".format(nosepoint[0][i],nosepoint[1][i],nosepoint[2][i],2))

    for i in range(mousepointp.shape[1]):
        fo.write("{} {} {} {}\n".format(mousepoint[0][i],mousepoint[1][i],mousepoint[2][i],3))

    for i in range(earpointp.shape[1]):
        fo.write("{} {} {} {}\n".format(earpoint[0][i],earpoint[1][i],earpoint[2][i],4))
    #print(str)
    #str=fo.read()
    #print("******************")
    #print(str)
    fi.close()
    fo.close()

if __name__ == '__main__':
    for i in range(1,151):
        path="./point_net_modified/Tester_{}/Blendshape".format(i)
        isExists=os.path.exists(path)
        if not isExists:
            os.makedirs(path)
        for j in range(47):
            filein="./point_net/Tester_{}/Blendshape/shape_{}.xyz".format(i,j)
            fileout="./point_net_modified/Tester_{}/Blendshape/shape_{}.xyzc".format(i,j)
            xyz2xyzc(filein,fileout)

#分割种类：五种，为眼睛，鼻子，嘴，耳朵和其它人脸点
#基本功能，将数据分类并且不同颜色显示出来，然后按1，2，3，4，0存储到新的xyzc文件中
#分割线：
# 1、z轴0以下且在x轴数量分布线（改方向上Y的最大和最小值之差突然增大）外为耳朵，其它z轴以下点加入0
# 2、嘴：y轴0右边且在脸平面上，其它为普通人脸点
# 3、鼻子：y轴0左边且在脸平面上
# 4、眼睛：y轴0左边且在脸平面下（暂定）